﻿using AiXiu.BLL;
using AiXiu.Common;
using AiXiu.DAL;
using AiXiu.IBLL;
using AiXiu.IDAL;
using AiXiu.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AiXiu.WebStite
{
    public partial class PersonalEdit : Page
    {
        private District district;
        private ListItem ddlTips = new ListItem("- 请选择 -", "");

        #region Page_Load 页面加载事件 
        /// <summary>
        /// 页面加载事件 页面加载输出用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                /*BindProvinces();*/
                // 读取用户资料
                TBUsers user = IdentityManager.ReadUser();
                // 显示用户资料
                txtNickName.Text = user.NickName ?? "未设置昵称";
                ddlSex.SelectedIndex = user.Sex;
                if (txtBirthday != null)
                {
                    txtBirthday.Text = user.Birthday + "";
                }
                //如果城市不为空 则显示省份
                if (!string.IsNullOrWhiteSpace(user.Address))
                {
                    string[] addressArray = user.Address.Split(' ');
                    //显示省份
                    BindProvinces(addressArray[0]);
                    //显示城市
                    BindCitys(addressArray[0], addressArray[1]);
                }
                else
                {
                    BindProvinces();
                }
                //兴趣爱好
                if (!string.IsNullOrWhiteSpace(user.Hobby))
                {
                    //拆分为数组
                    string[] hobbyArray = user.Hobby.Split(' ');
                    //for循环 显示选中状态
                    for (int i = 0; i < cblHobby.Items.Count; i++)
                    {
                        string value = cblHobby.Items[i].Value;
                        if (hobbyArray.Contains(value))
                        {
                            cblHobby.Items[i].Selected = true;
                        }
                    }
                }
            }
        }
        #endregion

        #region PersonalEdit 构造函数 加载省市信息
        /// <summary>
        /// 加载省市信息 构造函数
        /// </summary>
        public PersonalEdit()
        {
            using (FileStream fileStream = new FileStream(Server.MapPath("~/App_Data/district.json"), FileMode.Open))
            {
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.Default))
                {
                    string distictString = streamReader.ReadToEnd();
                    district = JsonConvert.DeserializeObject<District>(distictString);
                }
            }
        }
        #endregion

        #region BindCitys 绑定城市下拉列表
        /// <summary>
        /// 绑定城市下拉列表
        /// </summary>
        /// <param name="provinceName">省份名称</param>
        /// <param name="cityName">城市名称</param>
        public void BindCitys(string provinceName, string cityName = null)
        {
            //未选择省份时，清空城市列表
            if (string.IsNullOrWhiteSpace(provinceName))
            {
                ddlCity.Items.Clear();
                ddlCity.Items.Add(ddlTips);
                return;
            }
            //未查到省份时，清空城市列表
            Province province = district.Provinces.SingleOrDefault(m => m.ProvinceName == provinceName);
            if (province == null)
            {
                ddlCity.Items.Clear();
                ddlCity.Items.Add(ddlTips);
                return;
            }
            //绑定省份下的城市列表
            ddlCity.DataSource = province.Citys;
            ddlCity.DataValueField = "CityName";
            ddlCity.DataTextField = "CityName";
            ddlCity.DataBind();
            ddlCity.Items.Insert(0, ddlTips);
            //设置城市默认选项
            if (string.IsNullOrWhiteSpace(cityName))
            {
                ddlCity.SelectedIndex = 0;
            }
            else
            {
                ddlCity.SelectedValue = cityName;
            }

        }
        #endregion

        #region BindProvinces 绑定省份下拉列表
        /// <summary>
        /// 绑定省份下拉列表
        /// </summary>
        /// <param name="provinceName"></param>
        private void BindProvinces(string provinceName = null)
        {
            //绑定省份列表
            ddlProvince.DataSource = district.Provinces;
            ddlProvince.DataValueField = "ProvinceName";
            ddlProvince.DataTextField = "ProvinceName";
            ddlProvince.DataBind();
            ddlProvince.Items.Insert(0, ddlTips);
            //如果未获取到省份则显示“请选择”
            if (string.IsNullOrWhiteSpace(provinceName))
            {
                ddlProvince.SelectedIndex = 0;
            }
            else
            {
                ddlProvince.SelectedValue = provinceName;
            }

        }
        #endregion

        #region btnProfile_Click 点击按钮事件实现修改信息功能
        /// <summary>
        /// 点击按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnProfile_Click(object sender, EventArgs e)
        {
            //读取当前用户信息
            TBUsers profile = IdentityManager.ReadUser();
            profile.NickName = txtNickName.Text;
            profile.Sex = ddlSex.SelectedIndex;
            if (!string.IsNullOrEmpty(txtBirthday.Text))profile.Birthday = DateTime.Parse(this.txtBirthday.Text);
            //对省市进行拼接
            profile.Address = $"{ddlProvince.SelectedValue} " +
                $"{ ddlCity.SelectedValue}";
            //找到省市信息
            List<string> hobbyList = new List<string>();
            foreach (ListItem item in cblHobby.Items)
            {
                if (item.Selected) hobbyList.Add(item.Value);
            }
            profile.Hobby = string.Join(" ", hobbyList);
            //在数据库更新资料
            IUserManger userManger = new UserManger();
            OperResult<TBUsers> editResult = userManger.EditWithoutAvatar(profile);
            if (editResult.StatusCode == StatusCode.Succeed)
            {
                //重新缓存用户资料
                IdentityManager.SaveUser(profile);
                Response.Redirect("Personal.aspx");
            }
            else
            {
                this.Alert("deiterror", editResult.Message);
            }

        }
        #endregion

        #region ddlProvince_SelectedIndexChanged 城市下拉框绑定
        /// <summary>
        /// 城市下拉框绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
        {
            string provinceName = ddlProvince.SelectedValue;
            BindCitys(provinceName);
        }
        #endregion
    }
}